package jgrouse.jgdoc.ant;

import java.io.File;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import jgrouse.jgdoc.xslt.FastProcessor;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;

public class FastXsltTask extends Task
{
	private Project m_project;
	private String m_template;
	private String m_source;
	private Map<String, String> m_standardOptions;
	private List<Output> m_output;
	
	public FastXsltTask()
	{
		m_standardOptions = new HashMap<String, String>();
		m_output = new LinkedList<Output>();
	}
	
	public void setProject(Project pProject)
	{
		m_project = pProject;
	}
	
	public Project getProject()
	{
		return m_project;
	}
	
	public void execute() throws BuildException
	{
		FastProcessor fp = new FastProcessor();
		File f = new File(m_source);
		if (!f.isAbsolute())
		{
			f = new File(m_project.getBaseDir(), m_source);
		}
		fp.setInputFile(f);
		f = new File(m_template);
		if (!f.isAbsolute())
		{
			f = new File(m_project.getBaseDir(), m_template);
		}
		fp.setTemplateFile(new File(m_template));
		fp.setOptions(m_standardOptions);
		List<FastProcessor.ProcessorParams> list = new LinkedList<FastProcessor.ProcessorParams>();
		for (Output o : m_output)
		{
			FastProcessor.ProcessorParams pp = new FastProcessor.ProcessorParams();
			f = new File(o.m_file);
			if (!f.isAbsolute())
			{
				f = new File(m_project.getBaseDir(), o.m_file);
			}
			pp.setOutputFile(f);
			pp.setPrivateOptions(o.m_options);
			list.add(pp);
		}
		fp.setParams(list);
		try
		{
			fp.process();
		}
		catch (Exception ex)
		{
			throw new BuildException(ex);
		}
		
	}

	public String getTemplate()
	{
		return m_template;
	}

	public void setTemplate(String pTemplate)
	{
		m_template = pTemplate;
	}

	public String getSource()
	{
		return m_source;
	}

	public void setSource(String pSource)
	{
		m_source = pSource;
	}
	
	public void addConfiguredParam(Param param)
	{
		m_standardOptions.put(param.getKey(), param.getValue());
	}
	
	public void addConfiguredOutput(Output output)
	{
		m_output.add(output);
	}

	public static class Output
	{
		private Map<String, String> m_options;
		private String m_file;
		
		public Output()
		{
			m_options = new HashMap<String, String>();
		}
		
		public void addConfiguredParam(Param param)
		{
			m_options.put(param.getKey(), param.getValue());
		}

		public String getFile()
		{
			return m_file;
		}

		public void setFile(String pFile)
		{
			m_file = pFile;
		}

			}
	
}
